<template>
  <div class="app-container">
    <div class="table-container">
      <Form ref="form" :model="formInline" >
        <Row>
          <Col span="5" style="margin-right:20px">
            <FormItem :prop="'brandName'" :rules="{required: true, message: '请选择品牌'}">
              <Select
                v-model="formInline.brandName"
                filterable
                placeholder="品牌"
                @on-change="brandsChange"
              >
                <Option
                  v-for="(option, index) in brandOptions"
                  :value="option.brandId"
                  :key="index"
                  >{{ option.brandName }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="5" style="margin-right:20px">
            <FormItem :prop="'costCenterName'" :rules="{required: true, message: '请选择成本中心'}">
              <Select
                v-model="formInline.costCenterName"
                filterable
                placeholder="成本中心"
              >
                <Option
                  v-for="(option, index) in costCenterList"
                  :value="option.id"
                  :key="index"
                  >{{ option.costCenterName }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="5" style="margin-right:20px">
            <FormItem :prop="'firstMaterial'" :rules="{required: true, message: '请选择物料一级类目'}">
              <Select
                v-model="formInline.firstMaterial"
                filterable
                placeholder="物料一级类目"
              >
                <Option
                  v-for="(option, index) in materialList"
                  :value="option.firstMaterial"
                  @click.native="firstChange(option)"
                  :key="index"
                  >{{ option.firstMaterial }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem :prop="'secondMaterial'" :rules="{required: true, message: '请选择物料二级类目'}">
              <Select
                v-model="formInline.secondMaterial"
                filterable
                placeholder="物料二级类目"
              >
                <Option
                  v-for="(option, index) in secondMaterialList"
                  :value="option.secondMaterial"
                  @click.native="secongChange(option)"
                  :key="index"
                  >{{ option.secondMaterial }}</Option
                >
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <TaskEntryItem
        ref="taskEntryItem"
        :MaterialList="threadMaterialList"
        @handlerReset="handlerReset"
        @handlerSubmit="handlerSubmit"
      ></TaskEntryItem>
    </div>
  </div>
</template>

<script>
import TaskEntryItem from './components/taskEntryItem.vue'
import { getbrandMaterialNew, getCostCenter, addTask } from '@/api/taskMange'
import format from "date-format";
import { mapGetters } from 'vuex';

export default {
  data() {
    return {
      // 品牌列表
      brandOptions: [],
      // 成本中心列表
      costCenterList: [],
      // 物料列表
      materialList: [],
      // 二级物料列表
      secondMaterialList: [],
      // 三级物料列表
      threadMaterialList: [],
      // 可上传优秀数量
      goodCount: 0,
      formInline: {
        brandName: "",
        costCenterName: '',
        firstMaterial: '',
        secondMaterial: '',
      }

    };
  },
  created() {
    this.getBrandNew()
  },
  methods: {
    // 提交录入
    handlerSubmit(form) {
      this.$refs['form'].validate( async (valid) => {
        if (valid) {
          let goodsWorks = 0
          const requestData = []
          // this.$Message.success('Success!');
          form.items.forEach(item => {
            if(item.isCheck) {
              goodsWorks += 1
            }
            if(item.count) {
              requestData.push({
                userId: this.userId,
                brandId: this.formInline.brandName,
                costCenterId: this.formInline.costCenterName,
                materialId: item.detailedPurpose,
                materialCount: item.count,
                fileUrls: item.imgUrl,
                finishTime: item.dataTime ? format("yyyy-MM-dd", new Date(item.dataTime)) : '',
                goodWork: item.isCheck ? 1 : 0
              })
            }
          })
          if(goodsWorks > (5 - this.goodCount)) {
            return this.$Message.error(`每月一人最多可上传5个优秀作品`);
          }
          try {
            await addTask(requestData)
            this.$Message.success('录入成功');
          } catch(err) {
            return this.$Message.error(err);
          }
        } else {
          this.$Message.error('请选择完整信息');
        }
      })
    },
    secongChange(item) {
      this.threadMaterialList = item.threadMaterialDtos
    },

    firstChange(item) {
      this.secondMaterialList = item.secondMaterials
    },

    // 清空信息
    handlerReset() {
      this.$refs.form.resetFields();
      this.formInline.brandName = ''
      this.formInline.costCenterName = ''
      this.formInline.firstMaterial = ''
      this.formInline.secondMaterial = ''
    },

    // 获取品牌下对应的成本中心
    async brandsChange(id) {
      if(!id) return
      this.costCenterList = []
      const { data = [] } = await getCostCenter(id)
      this.costCenterList = data
    },

    // 获取全部品牌
    async getBrandNew() {
      try {
        const { data = {}} = await getbrandMaterialNew()
        this.brandOptions = data.brands
        this.materialList = data.material
        this.goodCount = data.goodCount
      } catch(err) {
        return err
      }
    }
  },
  components: {
    TaskEntryItem
  },
  computed: {
    ...mapGetters(["userId"])
  }
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 20px 40px;
  min-height: 400px;
}
/deep/ .ivu-select-single .ivu-select-selection {
  border-radius: 18px;
  padding: 0 24px 0 16px;
}
/deep/ .ivu-select-single .ivu-select-input::-webkit-input-placeholder{
  color: #2e3773;
}
/deep/ .ivu-tag-red {
  border-color: #b9b9b9;
  background-color: #fff;
  border-radius: 10px;
}
/deep/ .ivu-tag-red .ivu-tag-text {
  color: #2e3773 !important;
}
/deep/ .ivu-form-item-error-tip {
  left: 10px
}
</style>
